from bs4 import BeautifulSoup
import requests, sys
import time

"""
类说明:下载《笔趣看》网小说《一念永恒》
Parameters:
    无
Returns:
    无
Modify:
    2017-09-13
"""
class downloader(object):

    def __init__(self):
        # self.server = 'http://www.biqukan.com/'
        self.server = 'https://www.biqukan8.cc'
        self.target = 'https://www.biqukan8.cc/1_1094/'
        self.headers = {
            "cookie": "bcolor=; font=; size=; fontcolor=; width=; Hm_lvt_d980a3f9499907d0586dbac4f3207804=1678246135,1678692242; Hm_lpvt_d980a3f9499907d0586dbac4f3207804=1678692267",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36"
        }
        self.names = []            #存放章节名
        self.urls = []            #存放章节链接
        self.nums = 0            #章节数

    """
    函数说明:获取下载链接
    Parameters:
        无
    Returns:
        无
    Modify:
        2017-09-13
    """
    def get_download_url(self):
        req = requests.get(url = self.target, headers=self.headers)
        print(req.status_code)
        req.encoding="gbk"
        print(req.encoding)
        html = req.text
        div_bf = BeautifulSoup(html, "html.parser")
        div = div_bf.find('div', class_ = 'listmain')
        chapters = div.find_all("a")
        self.nums = len(chapters)
        print(f"chapters number:{self.nums}")
        for chatpter in chapters:
            # print(chatpter.get_text())
            self.names.append(chatpter.get_text())
            self.urls.append(self.server + chatpter["href"])
        # a_bf = BeautifulSoup(str(div[0]))
        # a = a_bf.find_all('a')
        # self.nums = len(a[13:])                                #剔除不必要的章节，并统计章节数
        # for each in a[13:]:
        #     self.names.append(each.string)
        #     self.urls.append(self.server + each.get('href'))

    """
    函数说明:获取章节内容
    Parameters:
        target - 下载连接(string)
    Returns:
        texts - 章节内容(string)
    Modify:
        2017-09-13
    """
    def get_contents(self, target):
        req = requests.get(url = target, headers=self.headers)
        print(req.status_code)
        req.encoding = "gbk"
        html = req.text
        bf = BeautifulSoup(html, "html.parser")
        texts = bf.find_all('div', class_ = 'showtxt')
        texts = texts[0].text.strip()#replace('\xa0'*4,'\n\n')
        return texts

    """
    函数说明:将爬取的文章内容写入文件
    Parameters:
        name - 章节名称(string)
        path - 当前路径下,小说保存名称(string)
        text - 章节内容(string)
    Returns:
        无
    Modify:
        2017-09-13
    """
    def writer(self, name, path, text):
        write_flag = True
        with open(path, 'w', encoding='utf-8') as f:
            f.write(name + '\n')
            f.writelines(text)
            f.write('\n\n')

if __name__ == "__main__":
    dl = downloader()
    dl.get_download_url()
    print('《一年永恒》开始下载：')
    start = time.time()   #记录程序运行起始时间
    for i in range(0,1):
        print(f"下载章节:[{dl.names[i]}]")
        print(f"章节url:[{dl.urls[i]}]")
        dl.writer(dl.names[i], '一念永恒.txt', dl.get_contents(dl.urls[i]))
        # sys.stdout.write("  已下载:%.3f%%" %  float(i/dl.nums) + '\r')
        sys.stdout.flush()
    end = time.time()
    print(f'《一年永恒》下载完成,共耗时{float(end - start)}')